package com.ychs.dpmms.controller;

import com.ychs.dpmms.entity.*;
import com.ychs.dpmms.service.IBaseService;
import com.ychs.dpmms.util.Constants;
import com.ychs.dpmms.util.PasswordEncryption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * copyright(c)2021 YYB.ALL rights Reserved
 * <p>
 * 描述:用户Controller
 *
 * @author 原玉波
 * @version 1.0
 * @date 2021/9/3
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name="userService")
    private IBaseService<User> service;
    @Resource(name="developerService")
    private IBaseService<Developer> developerService;

    //添加方法
    @PostMapping("/add")
    public ResultMessage add(@Validated @RequestBody User user, BindingResult br , Map map) {
        logger.debug(user.toString());
        logger.debug("enter user add");
        String msg = "增加成功";
        boolean result = false;
        /*校验不通过，会有错误信息*/
        if (br.hasFieldErrors()) {
            for (FieldError fe : br.getFieldErrors()){
                if (!fe.getField().equals("user")) {
                    logger.debug("校验失败"+fe);
                    return new ResultMessage(false, null, "校验失败");
                }
            }
        }else{
            logger.debug("user="+user);

            //判断该用户是否已经存在
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("username", user.getUsername());
            int count = service.searchTotalNumber(conditions);
            //若查到该名称的数量大于等于1，则不添加，并返回信息，否则继续执行添加
            if(count>=1){
                msg = "该名称已经存在！";
            }else{
                result = service.add(user);
            }
        }
        logger.debug("user add result = "+ result);
        ResultMessage resultMessage = new ResultMessage(result, user, msg);
        return resultMessage;
    }

    //批量添加发展党员的 添加方法，在设定初始账户密码后，还应将其user id 赋值给developer 的 user
    @PostMapping("/addMulti")
    public ResultMessage addMulti(@Validated @RequestBody User user, BindingResult br , Map map) {
        logger.debug("enter user addMulti");
        String msg = "增加成功";
        boolean result = false;
        /*校验不通过，会有错误信息*/
        if (br.hasFieldErrors()) {
            for (FieldError fe : br.getFieldErrors()){
                if (!fe.getField().equals("user")) {
                    logger.debug("校验失败"+fe);
                    return new ResultMessage(false, null, "校验失败");
                }
            }
        }else{
            logger.debug("user="+user);
            //首先根据前台信息添加user信息
            //判断该用户是否已经存在
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("username", user.getUsername());
            int count = service.searchTotalNumber(conditions);
            //若查到该名称的数量大于等于1，则不添加，并返回信息，否则继续执行添加
            if(count>=1){
                msg = "添加失败！";
            }else{
                result = service.add(user);
            }
            logger.debug("user add result "+result);
            //如果添加成功，则执行developer中user的信息添加
            if (result) {
                //user的添加成功后会返回主键信息，可以直接setUser，user参数中包含了name信息，与developer中的name是一样的
                Developer developer = new Developer();
                developer.setUser(user);
                developer.setName(user.getName());
                Capacity capacity = new Capacity();
                capacity.setId(1);
                developer.setCapacity(capacity);
                developer.setBatch(Integer.parseInt(user.getRemark()));
                developer.setSubmitEnterApplicationDate(new Date());
                developer.setRemark("first");
                boolean developerResult = false;
                developerResult = developerService.add(developer);
                logger.debug("developerResult  ="+developerResult);

                //如果user和他对应的发展党员都成功添加了，设置结果为true
                if(developerResult){
                    result = true;
                }else{
                    //否则developer添加不成功，则认为这次多重添加是失败的，将原先添加的user删除
                    boolean removeResult = service.remove(user.getId());
                    msg = "添加失败";
                }

            }else{
                msg = "添加失败";
            }
        }
        logger.debug("user addMulti result = "+ result);
        ResultMessage resultMessage = new ResultMessage(result, user, msg);
        return resultMessage;
    }

    //修改方法
    @PostMapping("/modify")
    public ResultMessage modify(@Validated @RequestBody User user, BindingResult br , Map map) {
        logger.debug("enter user modify");
        String msg = "修改成功";
        boolean result = false;
        /*校验不通过，会有错误信息*/
        if (br.hasFieldErrors()) {
            for (FieldError fe : br.getFieldErrors()){
                if (!fe.getField().equals("user")) {
                    logger.debug("校验失败"+fe);
                    return new ResultMessage(false, null, "校验失败");
                }
            }
        }else{
            logger.debug("user乐="+user.toString());

            Map<String, Object> conditions = new HashMap<>();
            conditions.put("username", user.getUsername());
            conditions.put("notId", user.getId());
            int count = service.searchTotalNumber(conditions);
            //若查到该名称的数量大于等于1，则不添加，并返回信息，否则继续执行添加
            if(count>=1){
                msg = "该名称已经存在！";
            }else{
                Branch branch = user.getBranch();
                if (branch.getId() == 0) {
                    user.setBranch(null);
                }
                result = service.modify(user);
            }
        }
        logger.debug("user modify result = "+ result);
        ResultMessage resultMessage = new ResultMessage(result, user, msg);
        return resultMessage;
    }

    //查询方法
    @GetMapping("/search")
    public ResultMessage search(Integer limit, Integer page, Integer role,Integer state,Integer secondOrganization,Integer branch,String name) {
        Map<String, Object> conditions = new HashMap<>();

        if (role != null) {
            conditions.put("role", role);
        }
        if (name != null&&!"".equals(name)) {
            conditions.put("name", name);
        }
        if (state != null) {
            conditions.put("state", state);
        }
        if (secondOrganization != null) {
            conditions.put("secondOrganization", secondOrganization);
        }
        if (branch != null) {
            conditions.put("branch", branch);
        }

        int count = service.searchTotalNumber(conditions);

        if (limit != null && page != null) {
            conditions.put("begin", (page - 1) * limit);
            conditions.put("pageSize", limit);
        }

        List<User> userList = service.search(conditions);
        logger.debug("userList=" + userList.toString());
        ResultMessage resultMessage = new ResultMessage(true, userList, "" + count);
        return resultMessage;
    }

    //删除方法
    @PostMapping("/remove/{id}")
    public ResultMessage remove(@PathVariable("id") int id){
        logger.debug("enter user remove");
        logger.debug("id="+id);
        boolean result = service.remove(id);

        logger.debug("result = " + result);
        ResultMessage resultMessage =
                new ResultMessage(result, null, result?"删除成功":"删除失败");
        return resultMessage;
    }

    @PostMapping("/login")
    public ResultMessage login(String username,String password) {
        /*User user = service.login(username, password);
        ResultMessage resultMessage = new ResultMessage(user!=null? true:false, user, "");
        return resultMessage;*/
        boolean result = false;
        User user = new User();
        String msg = "登录成功";

        Map<String, Object> conditions = new HashMap<>();
        conditions.put("loginUsername", username);
        List<User> userList = service.search(conditions);
        logger.debug("userList.size="+userList.size());
        if (userList.size() == 1) {
            Map<String, Object> conditions2 = new HashMap<>();
            conditions2.put("id", userList.get(0).getId());
            conditions2.put("loginPassword", password);
            List<User> userList2 = service.search(conditions2);
            logger.debug("userList2.size="+userList2.size());
            logger.debug("userList2="+userList2.toString());
            if (userList2.size() == 1) {
                if(!userList2.get(0).getRemark().equals("wait")){
                    user = userList.get(0);
                    result = true;
                }else{
                    logger.debug("乐乐一");
                    result = false;
                    user = null;
                    msg = "多次登录失败，该账号当前已经无法登录，请稍后重试";
                }
            }else{//仅仅是密码错误
                result = false;
                user = null;
                msg = "密码错误，请重新输入";
                if(!userList.get(0).getRemark().equals("loginFail1")&&!userList.get(0).getRemark().equals("loginFail2")
                        &&!userList.get(0).getRemark().equals("loginFail3")&&!userList.get(0).getRemark().equals("wait")){
                    User newUser =  userList.get(0);
                    newUser.setRemark("loginFail1");
                    boolean modifyResult = service.modify(newUser);
                }else if (userList.get(0).getRemark().equals("loginFail1")) {
                    User newUser =  userList.get(0);
                    newUser.setRemark("loginFail2");
                    boolean modifyResult = service.modify(newUser);
                }else if (userList.get(0).getRemark().equals("loginFail2")) {
                    User newUser =  userList.get(0);
                    newUser.setRemark("loginFail3");
                    boolean modifyResult = service.modify(newUser);
                }else if (userList.get(0).getRemark().equals("loginFail3")) {
                    User newUser =  userList.get(0);
                    newUser.setRemark("wait");
                    boolean modifyResult = service.modify(newUser);
                }else if (userList.get(0).getRemark().equals("wait")) {
                    result = false;
                    user = null;
                    msg = "多次登录失败，该账号当前已经无法登录，请稍后重试";
                }
            }
        }else{
            user=null;
            msg = "请输入有效的账号";
        }
        ResultMessage resultMessage = new ResultMessage(result, user, msg);
        return resultMessage;
    }

    @PostMapping("/login2")
    public ResultMessage login2(String username,String password) {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("loginUsername", username);
        List<User> userList = service.search(conditions);
        logger.debug("userList.size="+userList.size());
        User user = userList.get(0);
        String[] fix = user.getPassword().split("-");
        String salt = fix[0];
        String cipherText = fix[1];
        boolean result = false;
        String msg = "成功";
        try {
            result = PasswordEncryption.authenticate(password, cipherText, salt);
            msg = result ? "成功" : "失败";
        } catch (NoSuchAlgorithmException e) {
            msg = "失败";
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            msg = "失败";
            e.printStackTrace();
        }
        ResultMessage resultMessage = new ResultMessage(result, user, msg);
        return resultMessage;
    }
}
